package com.panda.web.utils;

import com.panda.common.utils.StringUtils;
import com.panda.web.entity.wechat.WechatUser;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Component
public class WeChatUtlis {
    private static final String NO_CERTIFICATE = "没有";
    /**
     * HTTP GET 请求方法
     */
    public String httpGet(String requestUrl) throws Exception {
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }
    public static String httpGetTest(String requestUrl) throws Exception {
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }

    public static int calculateScore(WechatUser user) {
        int score = 0; // 初始分数为0分,满分100分

        // 1. 求职类型 央企+0分，国企+7分
        if ("国企".equals(user.getHuntingType())) {
            score += 7;
        }

        // 2. 学历 大专+0分，本科+5分，硕士+10分；
        if (StringUtils.isNotNull(user.getBackground())){
            if (Objects.equals(user.getBackground(),"本科")){
                score += 5;
            }else if (Objects.equals(user.getBackground(),"硕士")){
                score += 10;
            }
        }


        // 3. 政治面貌 党员或预备党员+5分，其他＋0分
        if ("中共党员".equals(user.getPolitics()) || "预备党员".equals(user.getPolitics())) {
            score += 5;
        }

        // 4. 求职地点和籍贯或毕业院校所在城市是否重合 ,求职地点和籍贯或毕业院校所在城市只要有一个重合的，+5分，一个都不重合的+0分；
        // 判断是否匹配
        boolean isMatch = isLocationMatch(user.getSearchLocation(), user.getNativePlace(), user.getGraduateCity());
        if (isMatch) {
            score += 5;
        }


        // 5. 毕业院校类别 普通本科+0分，211＋5分，985＋10分；
        switch (user.getGraduateType()) {
            case "211":
                score += 5;
                break;
            case "985":
                score += 10;
                break;
            default:
                break;
        }

        // 6. 实习或项目经历 实习或项目经历：1段＋5分，2段及以上+10分，没有+0分；
        if (user.getProjectExperience() != null) {
            if (Objects.equals(user.getProjectExperience(),"1段")) {
                score += 5;
            } else if (Objects.equals(user.getProjectExperience(),"2段及以上")) {
                score += 10;
            }
        }

        // 7. 就读专业 工科+15分，经济学、法学、理学＋10分，管理学、医学、农学+5分，其他+0分；
        switch (user.getMajor()) {
            case "工科":
                score += 15;
                break;
            case "经济学":
            case "法学":
            case "理学":
                score += 10;
                break;
            case "管理学":
            case "医学":
            case "农学":
                score += 5;
                break;
            default:
                break;
        }

        // 8. 英语6级语言能力 过六级+5分，没过+0分；
        if ("是".equals(user.getEnglishSix())) {
            score += 5;
        }

        // 9. 计算机能力 过二级+5分，没过+0分；
        if ("是".equals(user.getComputerTwo())) {
            score += 5;
        }

        // 10. 与本专业相关的技能证书或资格证书 1个+3分，2个及以上+7分，没有+0分
        if (user.getSkillCertificate() != null) {
            String certificateCount = user.getSkillCertificate();
            if (Objects.equals(certificateCount,"1个")) {
                score += 3;
            } else if (Objects.equals(certificateCount,"2个及以上")) {
                score += 7;
            }
        }

        // 11. 在学生会或社团 1.担任副部长以上职级；2.组织过活动或比赛，符合其中一个的+5分，没有+0分；
        if (StringUtils.isNotNull(user.getCampusPractice())){
            String campusPractice = user.getCampusPractice();
            if (!Objects.equals(campusPractice,NO_CERTIFICATE)){
                score += 5;
            }
        }


        // 12. 获奖情况 国家级+10分，省部级+8分，市级+5分，校级+3分。
        if (user.getScholarship() != null) {
            if (user.getScholarship().contains("国家级")) {
                score += 10;
            } else if (user.getScholarship().contains("省部级")) {
                score += 8;
            } else if (user.getScholarship().contains("市级")) {
                score += 5;
            } else if (user.getScholarship().contains("校级")) {
                score += 3;
            }
        }

        // 13. 性别 男生+6分，女生+0分。
        if ("男".equals(user.getSex())) {
            score += 6;
        }
        // 特殊说明 年龄不符合的，总得分✖️0.7，没过4级的，总得分✖️0.6，不是应届的，总得分✖️0.5。

        if (Objects.equals(user.getStressStatus(),"否")){//不是应届
            score *= 0.5;
        }else {
            if (Objects.equals(user.getBackground(),"大专")||Objects.equals(user.getBackground(),"本科")){
                if (user.getAge() >=25){
                    score *= 0.7;
                }
            }else if (Objects.equals(user.getBackground(),"硕士")){
                if (user.getAge()>=28) {
                    score *= 0.7;
                }

            }

        }

        if ("否".equals(user.getEnglishFour())) {
            score *= 0.6;
        }


        return score;
    }


    /**
     * 就业竞争力
     */
    public static List<String> getEmploymentCompetence(WechatUser user){
        List<String> competence = new ArrayList<>();
        if (!Objects.equals(user.getBackground(),null)&&Objects.equals(user.getBackground(),"硕士")){
            competence.add("学历优势");
        }
        if (!Objects.equals(user.getPolitics(),null)&&Objects.equals(user.getPolitics(),"中共党员")||Objects.equals(user.getPolitics(),"预备党员")){
            competence.add("党员优势");
        }
        if (!Objects.equals(user.getGraduateType(),null)&&Objects.equals(user.getGraduateType(),"211")||Objects.equals(user.getGraduateType(),"985")){
            competence.add("学校优势");
        }
        if (StringUtils.isNotNull(user.getProjectExperience())){
            if (!Objects.equals(user.getProjectExperience(),NO_CERTIFICATE)){
                competence.add("实习经验优势");
            }

        }
        List<String> majorList = List.of("工科", "经济学", "法学", "理学", "管理学", "医学", "农学");
        if (majorList.contains(user.getMajor())) {
            competence.add("专业优势");
        }
        if (!Objects.equals(user.getEnglishSix(),null)&&Objects.equals(user.getEnglishSix(),"是")){
            competence.add("语言优势");
        }
        if (!Objects.equals(user.getComputerTwo(),null)&&Objects.equals(user.getComputerTwo(),"是")){
            competence.add("证书优势");
        }
        if (StringUtils.isNotNull(user.getSkillCertificate())){
            if (!Objects.equals(user.getSkillCertificate(),NO_CERTIFICATE)){
                competence.add("技能优势");
            }
        }
        if (StringUtils.isNotNull(user.getCampusPractice())){
            if (!Objects.equals(user.getCampusPractice(),NO_CERTIFICATE)){
                competence.add("校园实践优势");
            }
        }
        if (!Objects.equals(user.getScholarship(),null) &&
                (user.getScholarship().contains("国家级") || user.getScholarship().contains("省部级") || user.getScholarship().contains("市级"))) {
            competence.add("荣誉优势");
        }
        //9.笔试题
        List<String> gdDA =new ArrayList<>(Arrays.asList("B","C","A","B","C","A","A","A","D","D"));
        String bishi = user.getBishi();
        String delimiter = ","; // 分隔符

        List<String> bishiList = convertStringToList(bishi, delimiter);
        //固定答案
        int biShiScore = calculateScore(gdDA, bishiList);//笔试分数
        if (biShiScore>=70){
            competence.add("基础扎实");
        }
        return competence;
    }

    /**
     * 就业提升建议
     */
    public static List<String> getEmploymentPromotionProposal(WechatUser user, Integer score){
        List<String> promotionProposal = new ArrayList<>();
        // 1. 总体得分和央企目标
        if (score < 60 && Objects.equals(user.getHuntingType(), "央企")) {
            promotionProposal.add("央企风险过高，建议适当降低目标。");
        }

        // 2. 学历是大专
        if (!Objects.equals(user.getBackground(), null)) {
            if (Objects.equals(user.getBackground(), "大专")) {
                promotionProposal.add("建议提升学历。");
            }
            // 3. 本科及以下且专业为理、医、文、史、哲、艺术学、教育学
            else if (Objects.equals(user.getBackground(), "本科")
                    && !Objects.equals(user.getMajor(), null)
                    && (Objects.equals(user.getMajor(), "理科")
                    || Objects.equals(user.getMajor(), "医学")
                    || Objects.equals(user.getMajor(), "文学")
                    || Objects.equals(user.getMajor(), "史学")
                    || Objects.equals(user.getMajor(), "哲学")
                    || Objects.equals(user.getMajor(), "艺术学")
                    || Objects.equals(user.getMajor(), "教育学"))) {
                promotionProposal.add("建议提升学历。");
            }
        }

        // 4. 非应届学生
        if (!Objects.equals(user.getStressStatus(), null) && Objects.equals(user.getStressStatus(), "否")) {
            promotionProposal.add("非应届学生，会被视为社招人员，降低竞争力。");
        }

        // 5. 超年龄学生
        if (!Objects.equals(user.getAge(), null) && !Objects.equals(user.getBackground(), null)) {
            boolean isUndergraduate = "大专".equals(user.getBackground()) || "本科".equals(user.getBackground());
            boolean isOverAgeForUndergraduate = isUndergraduate && user.getAge() > 25;

            boolean isMaster = "硕士".equals(user.getBackground());
            boolean isOverAgeForMaster = isMaster && user.getAge() > 28;

            if (isOverAgeForUndergraduate || isOverAgeForMaster) {
                promotionProposal.add("年龄不占优势，会被视为社招人员，降低竞争力。");
            }
        }

        // 6. 求职地点与户籍地或院校所在地是否重合
        boolean isMatch = isLocationMatch(user.getSearchLocation(), user.getNativePlace(), user.getGraduateCity());
        if (!isMatch) {
            promotionProposal.add("尽量选择户籍所在地或院校所在地进行投递，央国企有地方保护政策。");
        }

        // 7. 无实习或项目经历
        if (StringUtils.isNotNull(user.getProjectExperience())){
            if (Objects.equals(user.getProjectExperience(), NO_CERTIFICATE)){
                promotionProposal.add("央国企很重视实习或项目经历，建议积累相关实习经历，提高综合竞争力。");
            }
        }

        // 8. 未过英语四级
        if (Objects.equals(user.getEnglishFour(), null) || Objects.equals(user.getEnglishFour(), "否")) {
            promotionProposal.add("英语四级是大多数央国企的必要要求，建议提升英语能力，通过四级或考取其他英语证书。");
        }
        //9.笔试题
        List<String> gdDA =new ArrayList<>(Arrays.asList("B","C","A","B","C","A","A","A","D","D"));
        String bishi = user.getBishi();
        String delimiter = ","; // 分隔符

        List<String> bishiList = convertStringToList(bishi, delimiter);
        //固定答案
        int biShiScore = calculateScore(gdDA, bishiList);//笔试分数
        if (biShiScore<60){
            promotionProposal.add("央国企笔试很重要，一考定局，要加紧笔试的联系和准备。");
        }
        //10.
        if (score>=70){
            promotionProposal.add("您的就业竞争力较高，已经超越了75%以上的求职者，建议精准选择岗位，认真理解企业招聘需求，为申请岗位定制化简历及网申，特别要认准准备笔面试内容。笔试多刷题，面试多做模拟训练。");
        }else {
            promotionProposal.add("要求职央国企，您还要做好全面准备，精准选择岗位，认真理解企业招聘需求，为申请岗位定制化简历及网申，特别要认准准备笔面试内容。笔试多刷题，面试多做模拟训练。");
        }
        return promotionProposal;
    }

    public static List<String> convertStringToList(String input, String delimiter) {
        if (input == null || input.isEmpty()) {
            throw new IllegalArgumentException("输入字符串不能为空");
        }
        return Arrays.asList(input.split(delimiter));
    }

    public static int calculateScore(List<String> answer, List<String> response) {
        if (answer.size() != response.size()) {
            throw new IllegalArgumentException("答案和答题结果的长度必须相同");
        }

        int score = 0;
        for (int i = 0; i < answer.size(); i++) {
            if (answer.get(i).equals(response.get(i))) {
                score += 10; // 每答对一题加10分
            }
        }
        return score;
    }








    /**
     * 标准化地址（去掉省、市、区等后缀）
     */
    private static String normalizeAddress(String address) {
        if (address == null) {
            return "";
        }
        return address.replace("省", "")
                .replace("市", "")
                .replace("区", "")
                .replace("县", "")
                .trim();
    }

    /**
     * 判断两个地址是否匹配
     */
    private static boolean isAddressMatch(String address1, String address2) {
        if (address1 == null || address2 == null) {
            return false;
        }
        String normalizedAddress1 = normalizeAddress(address1);
        String normalizedAddress2 = normalizeAddress(address2);
        // 使用包含关系判断
        return normalizedAddress1.contains(normalizedAddress2) || normalizedAddress2.contains(normalizedAddress1);
    }

    /**
     * 判断求职地点和籍贯或毕业院校所在城市是否匹配
     */
    public static boolean isLocationMatch(String searchLocation, String nativePlace, String graduateCity) {
        // 将各城市字符串拆分成单个城市
        String[] searchCities = searchLocation.split("，");
        String[] nativeCities = nativePlace.split("省|市"); // 移除省或市的部分，提取城市名
        String[] graduateCities = graduateCity.split("省|市");

        // 遍历求职地点中的城市，检查是否与籍贯或毕业院校城市有重合
        for (String searchCity : searchCities) {
            for (String nativeCity : nativeCities) {
                if (searchCity.contains(nativeCity.trim())) { // 处理空格
                    return true; // 找到重合，返回true
                }
            }
            for (String graduateCityStr : graduateCities) {
                if (searchCity.contains(graduateCityStr.trim())) { // 处理空格
                    return true; // 找到重合，返回true
                }
            }
        }

        // 如果没有重合，返回false
        return false;
    }



}